package com.weirblog.resource.permission;

import io.vertx.core.json.JsonObject;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;

import com.weirblog.entity.Tmenu;
import com.weirblog.entity.Users;
import com.weirblog.service.LoginService;
import com.weirblog.util.AesEncyptUtil;
import com.weirblog.vo.LoginUserVo;

import javax.annotation.security.PermitAll;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 登录生成token
 * 
 * @author weir
 *
 */
@Path("/")
@ApplicationScoped
public class LoginResource {

	@Inject
	TokenService tokenService;
	@Inject
	LoginService loginService;

	@GET
	@Path("init")
	public String init() {
		loginService.init();
		return "ok";
	}

	@PermitAll
	@POST
	@Path("login")
	public Response login(@RequestBody LoginUserVo user) {
		Users u = Users.find("userName", user.username).firstResult();
		if (u == null) {
			return Response.status(Status.BAD_REQUEST).entity(
					new JsonObject().put("message", "用户不存在")).build();
		}
		List<Tmenu> modules = 
				Tmenu.getEntityManager().createNativeQuery("select m.* from Tmenu m INNER JOIN perm_role_permission rm on m.id = rm.permission_id "
						+ "INNER JOIN perm_user_role ur on rm.role_id=ur.role_id where ur.user_id = ?", Tmenu.class)
				.setParameter(1, u.id).getResultList();
		if (!user.password.equals(u.userPwd)) {
			return Response.status(Status.BAD_REQUEST).entity(new JsonObject().put("message", "用户名或密码错误")).build();
		}
		Set<String> codes = modules.stream().map(Tmenu::getCode).collect(Collectors.toSet());
		u.moduleCodes = codes;
		String ujson = new JsonObject().put("user", u).toString();
		String token = tokenService.generateToken(u.email, ujson, codes);
		u.token = token;
		return Response.ok().entity(
				new JsonObject()
				.put("data", u)).build();
	}
	
}
